<template>
  <div class="va-df-rich-text">
    <iframe ref="iframe" src="javascript:void(0);">
    </iframe>
  </div>
</template>

<script>
  export default {
    props: {
      value: {},
      field: Object,
      disabled: Boolean
    },
    data () {
      return {
        html: ''
      }
    },
    mounted () {
      this.updateHtml()
    },
    methods: {
      rendToIFrame () {
        let cont = ''
        if (this.html) {
          if (this.html.indexOf('<body>') === -1) {
            cont = `<html>${this.field.mobile ? '<head><meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0"></head>' : ''}<body>${this.html}</body></html>`
          } else {
            cont = this.html
          }
        }
        this.$nextTick(() => {
          if (this.$refs.iframe.contentWindow.document.body) {
            this.$refs.iframe.contentWindow.document.body.innerText = ''
          }
          this.$refs.iframe.contentWindow.document.write(cont)
        })
      },
      updateHtml () {
        if (this.field.infoRenderer) {
          let rst = this.field.infoRenderer(this.value)
          if (rst && rst.then) {
            rst.then(data => {
              this.html = data
            })
          } else {
            this.html = rst
          }
        } else {
          this.html = this.value
        }
      }
    },
    watch: {
      html () {
        this.rendToIFrame()
      },
      value () {
        this.updateHtml()
      }
    }
  }
</script>
